import Vue from 'vue'
import VueRouter from 'vue-router'
// 使用
Vue.use(VueRouter)
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
// 重写push方法，解决多次点击搜索报错问题
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
// 重写replace方法
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}

import routes from './routes'
const router = new VueRouter({
    routes,
    // 路由跳转时，使滚动条在最上面（滚动行为）
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})
// 引入store
import store from '@/store'
// 全局前置路由守卫
router.beforeEach(async (to,from,next)=>{
    // store.watch((store)=>store.loginAndRegister.userInfo,(userInfo)=>{
    //     // console.log('***********');
    //     // console.log(userInfo);
    //     console.log(userInfo.name);
    //     // userName = userInfo.name
    //     // return userInfo.name
    // })
    if(localStorage.getItem('token')){
        // 如果已经登录，想要进入登录或注册页面，进不去，直接跳到home
        if(to.path==='/login'||to.path==='/register') next('/')
        else{
            // 登陆了，但是进入其他页面的时候，要重新获取用户信息展示
            try {
                await store.dispatch('getUserInfoByToken')
                next()
            } catch (error) {
                // 使token失效，重新登录
                store.dispatch('logout')
                next('/login')
            }
        }
    }else{
        // 没有登录
        // console.log(to.path);
        if(to.path==='/trade'||to.path==='/pay'||to.path==='/paySuccess'||to.path==='/center/myOrder'){
            // 以query参数保存当前点击的组件路径
            next('login?redirect='+to.path)
        }
        next()
    }

})
export default router